package authenum

import (
	"fmt"
	"yunj/pkg/yunj/core/builder/builderdto"
	"yunj/pkg/yunj/core/builder/builderenum"
	"yunj/pkg/yunj/core/enum"
	"yunj/pkg/yunj/util"
)

// 定义常量
const (
	// 数据查看
	CHILD_AUTH_NODE_VIEW string = "view"

	// 数据筛选
	CHILD_AUTH_NODE_FILTER string = "filter"

	// 数据操作
	CHILD_AUTH_NODE_ACTION string = "action"

	// 新增
	CHILD_AUTH_NODE_ADD string = "add"

	// 编辑
	CHILD_AUTH_NODE_EDIT string = "edit"

	// 详情查看
	CHILD_AUTH_NODE_EDIT_DETAIL string = "edit_detail"

	// 提交
	CHILD_AUTH_NODE_EDIT_SUBMIT string = "edit_submit"

	// 排序
	CHILD_AUTH_NODE_SORT string = "sort"

	// 移入回收站
	CHILD_AUTH_NODE_RECYLE_BIN string = "recyle_bin"

	// 恢复正常
	CHILD_AUTH_NODE_NORMAL string = "normal"

	// 删除
	CHILD_AUTH_NODE_DELETED string = "deleted"

	// 导出
	CHILD_AUTH_NODE_EXPORT string = "export"

	// 导入
	CHILD_AUTH_NODE_IMPORT string = "import"
)

// 实现EnumInerface接口
type ChildAuthNode struct {
	enum.Enum[string]
}

func (e *ChildAuthNode) AllConstAttrs() map[string]map[string]any {
	return map[string]map[string]any{
		CHILD_AUTH_NODE_VIEW: {
			"desc":                     "数据查看",
			"parent":                   "",
			"sort":                     10,
			"authRequestMode":          REQUEST_MODE_INTERNAL_ROUTER,
			"authPageOpen":             PAGE_OPEN_NIL,
			"authRequestUrl":           "/",
			"authRequestMethod":        REQUEST_METHOD_GET,
			"authRequestRequireParams": []map[string]any{},
		},
		CHILD_AUTH_NODE_FILTER: {
			"desc":   "数据筛选",
			"parent": "",
			"sort":   20,
		},
		CHILD_AUTH_NODE_ACTION: {
			"desc":   "数据操作",
			"parent": "",
			"sort":   30,
		},
		CHILD_AUTH_NODE_ADD: {
			"desc":            "新增",
			"parent":          CHILD_AUTH_NODE_ACTION,
			"sort":            40,
			"authRequestMode": REQUEST_MODE_INTERNAL_ROUTER,
			"authPageOpen":    PAGE_OPEN_POPUP,
			"authRequestUrl":  "/add",
		},
		CHILD_AUTH_NODE_EDIT: {
			"desc":   "编辑",
			"parent": CHILD_AUTH_NODE_ACTION,
			"sort":   50,
		},
		CHILD_AUTH_NODE_EDIT_DETAIL: {
			"desc":              "详情查看",
			"parent":            CHILD_AUTH_NODE_EDIT,
			"sort":              60,
			"authRequestMode":   REQUEST_MODE_INTERNAL_ROUTER,
			"authPageOpen":      PAGE_OPEN_POPUP,
			"authRequestUrl":    "/edit",
			"authRequestMethod": REQUEST_METHOD_GET,
		},
		CHILD_AUTH_NODE_EDIT_SUBMIT: {
			"desc":              "提交",
			"parent":            CHILD_AUTH_NODE_EDIT,
			"sort":              70,
			"authRequestMode":   REQUEST_MODE_INTERNAL_ROUTER,
			"authRequestUrl":    "/edit",
			"authRequestMethod": REQUEST_METHOD_POST,
			"authRequestRequireParams": []map[string]any{
				{
					"key":   "builder_async_type",
					"value": "submit",
				},
			},
		},
		CHILD_AUTH_NODE_SORT: {
			"desc":              fmt.Sprintf("排序（event_code=%s）", builderenum.TABLE_EVENT_TYPE_SORT),
			"parent":            CHILD_AUTH_NODE_ACTION,
			"sort":              80,
			"authRequestMode":   REQUEST_MODE_INTERNAL_ROUTER,
			"authRequestUrl":    "/",
			"authRequestMethod": REQUEST_METHOD_POST,
			"authRequestRequireParams": []map[string]any{
				{
					"key":   "builder_async_type",
					"value": "event",
				},
				{
					"key":   "event_code",
					"value": builderenum.TABLE_EVENT_TYPE_SORT,
				},
			},
		},
		CHILD_AUTH_NODE_RECYLE_BIN: {
			"desc":              fmt.Sprintf("移入回收站（event_code=%s）", builderenum.TABLE_EVENT_TYPE_RECYLE_BIN),
			"parent":            CHILD_AUTH_NODE_ACTION,
			"sort":              90,
			"authRequestMode":   REQUEST_MODE_INTERNAL_ROUTER,
			"authRequestUrl":    "/",
			"authRequestMethod": REQUEST_METHOD_POST,
			"authRequestRequireParams": []map[string]any{
				{
					"key":   "builder_async_type",
					"value": "event",
				},
				{
					"key":   "event_code",
					"value": builderenum.TABLE_EVENT_TYPE_RECYLE_BIN,
				},
			},
		},
		CHILD_AUTH_NODE_NORMAL: {
			"desc":              fmt.Sprintf("恢复正常（event_code=%s）", builderenum.TABLE_EVENT_TYPE_NORMAL),
			"parent":            CHILD_AUTH_NODE_ACTION,
			"sort":              100,
			"authRequestMode":   REQUEST_MODE_INTERNAL_ROUTER,
			"authRequestUrl":    "/",
			"authRequestMethod": REQUEST_METHOD_POST,
			"authRequestRequireParams": []map[string]any{
				{
					"key":   "builder_async_type",
					"value": "event",
				},
				{
					"key":   "event_code",
					"value": builderenum.TABLE_EVENT_TYPE_NORMAL,
				},
			},
		},
		CHILD_AUTH_NODE_DELETED: {
			"desc":              fmt.Sprintf("删除（event_code=%s）", builderenum.TABLE_EVENT_TYPE_DELETED),
			"parent":            CHILD_AUTH_NODE_ACTION,
			"sort":              110,
			"authRequestMode":   REQUEST_MODE_INTERNAL_ROUTER,
			"authRequestUrl":    "/",
			"authRequestMethod": REQUEST_METHOD_POST,
			"authRequestRequireParams": []map[string]any{
				{
					"key":   "builder_async_type",
					"value": "event",
				},
				{
					"key":   "event_code",
					"value": builderenum.TABLE_EVENT_TYPE_DELETED,
				},
			},
		},
		CHILD_AUTH_NODE_EXPORT: {
			"desc":              "导出",
			"parent":            CHILD_AUTH_NODE_ACTION,
			"sort":              120,
			"authRequestMode":   REQUEST_MODE_INTERNAL_ROUTER,
			"authRequestUrl":    "/",
			"authRequestMethod": REQUEST_METHOD_POST,
			"authRequestRequireParams": []map[string]any{
				{
					"key":   "builder_async_type",
					"value": "exportTask",
				},
			},
		},
		CHILD_AUTH_NODE_IMPORT: {
			"desc":            "导入",
			"parent":          CHILD_AUTH_NODE_ACTION,
			"sort":            130,
			"authRequestMode": REQUEST_MODE_INTERNAL_ROUTER,
			"authPageOpen":    PAGE_OPEN_POPUP,
			"authRequestUrl":  "/import",
		},
	}
}

// 获取权限parent_key
func (e *ChildAuthNode) GetAuthParentKey(prefix string) (res string) {
	res = prefix
	parent := e.GetAttr("parent")
	if parentStr, err := util.ToString(parent); err == nil && parentStr != "" {
		res += "_" + parentStr
	}
	return
}

// 获取权限page_open
func (e *ChildAuthNode) GetAuthRequestMode() (res uint8) {
	attrValue := e.GetAttr("authRequestMode")
	if enumValue, ok := RequestModeEnum.IsValue(attrValue); ok {
		res = enumValue
	} else {
		res = REQUEST_MODE_NIL
	}
	return
}

// 获取权限page_open
func (e *ChildAuthNode) GetAuthPageOpen() (res uint8) {
	pageOpen := e.GetAttr("authPageOpen")
	if enumValue, ok := PageOpenEnum.IsValue(pageOpen); ok {
		res = enumValue
	} else {
		res = PAGE_OPEN_NIL
	}
	return
}

// 获取权限request_url
func (e *ChildAuthNode) GetAuthRequestUrl(prefix string) (res string) {
	requestUrl := e.GetAttr("authRequestUrl")
	if requestUrlStr, err := util.ToString(requestUrl); err == nil && requestUrlStr != "" {
		res = prefix
		if requestUrlStr != "/" {
			res += requestUrlStr
		}
	}
	return
}

// 获取权限request_method
func (e *ChildAuthNode) GetAuthRequestMethod() (res string) {
	attrValue := e.GetAttr("authRequestMethod")
	if enumValue, ok := RequestMethodEnum.IsValue(attrValue); ok {
		res = enumValue
	} else {
		res = REQUEST_METHOD_ANY
	}
	return
}

// 获取权限request_method
func (e *ChildAuthNode) GetAuthRequestRequireParams(originLocation uint8) (res []map[string]any) {
	attrValue := e.GetAttr("authRequestRequireParams")
	if resValue, ok := attrValue.([]map[string]any); ok {
		res = resValue
	} else {
		res = []map[string]any{}
	}
	if originLocation == TYPE_SIDEBAR_MENU || originLocation == TYPE_TOP_MENU {
		res = append(res, map[string]any{
			"key":   "originLocation",
			"value": originLocation,
		})
	}
	return
}

// 获取权限sort
func (e *ChildAuthNode) GetAuthSort() (res uint16) {
	sort := e.GetAttr("sort")
	if sort != nil {
		if resValue, err := util.ToUint16(sort); err == nil {
			res = resValue
		}
	}
	return
}

// instanceCache 存储已经创建的实例
var childAuthNodeInstanceCache = make(map[string]*ChildAuthNode)

// 根据value获取枚举
func ChildAuthNodeByValue(value string) *ChildAuthNode {
	if instance, exists := childAuthNodeInstanceCache[value]; exists {
		return instance
	}
	e := &ChildAuthNode{}
	enum.SetEnumInstance(&e.Enum, e, value)
	childAuthNodeInstanceCache[value] = e
	return e
}

var ChildAuthNodeEnum *ChildAuthNode = func() *ChildAuthNode {
	e := &ChildAuthNode{}
	enum.SetEnumInstance(&e.Enum, e)
	return e
}()

var formTreeChildAuthNodes []*builderdto.FormTreeCheckNode

// 获取表单树子权限节点
func GetFormTreeChildAuthNodes() []*builderdto.FormTreeCheckNode {
	if len(formTreeChildAuthNodes) > 0 {
		return formTreeChildAuthNodes
	}
	sortConsts := ChildAuthNodeEnum.GetSortConsts()
	allConstAttrs := ChildAuthNodeEnum.AllConstAttrs()
	formTreeChildAuthNodes = make([]*builderdto.FormTreeCheckNode, 0, len(allConstAttrs))
	for _, enumValue := range sortConsts {
		constAttrs := allConstAttrs[enumValue]
		var pid any
		if constAttrs["parent"] != nil {
			pid = constAttrs["parent"]
		}
		var name string
		if constAttrs["desc"] != nil {
			name = constAttrs["desc"].(string)
		}
		formTreeChildAuthNodes = append(formTreeChildAuthNodes, &builderdto.FormTreeCheckNode{
			Id:   enumValue,
			Pid:  pid,
			Name: name,
		})
	}
	return formTreeChildAuthNodes
}
